package com.heima.user.filter;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 *
 */
@Component
@Slf4j
@Order(1)
@WebFilter(filterName = "appTokenFilter",urlPatterns = "/*")
public class AppTokenFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取请求头中的userId并放入一个新建的ApUser对象中
        // 获取请求头对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId) && Integer.parseInt(userId) != 0){
            // 说明是真实用户登陆，新建ApUser
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            // 赋值给ThreadLocal
            AppThreadLocalUtils.setUser(apUser);
            // 放行
        }
        filterChain.doFilter(servletRequest,servletResponse);

    }

    //
}
